<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

class OwnserviceControllerOwnservice extends JController
{
	function __construct() {
		parent::__construct();
	}

	/**
	 * Method select transfer
	 * 
	 * @return void
	 * @since 1.5
	*/

	function transfer() {
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		global $mainframe, $option;

		$session = & JFactory::getSession();
		$db		 = & JFactory::getDBO();
		$session->set('session', 1, $option);

		// Create the view
		$view = & $this->getView('ownservice', 'html');

		// Get/Create the model
		$model = & $this->getModel('ownservice');

		// Push the model into the view (as default)
		$view->setModel($model,true);

		// Set the layout
		$view->setLayout('transfer');

		$view->display();
	}

	function confirmdetail()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		global $mainframe, $option;

		//Initialise variables
		$session		= & JFactory::getSession();
		$db			= & JFactory::getDBO();
		$user			= & JFactory::getUser();

		$post = JRequest::get('post');

		//set data to session
		$session->set('datatransfer', $post, $option);

		//Get the model
		$model = $this->getModel('Ownservice');

		// Create the view
		$view = & $this->getView('ownservice', 'html');

		// Push the model into the view (as default)
		$view->setModel($model,true);

		// Set the layout
		$view->setLayout('detail');

		// Display the view
		$view->display();
	}

	/**
	 * Method to save transfer
	 *
	 * @return void
	 * @since 1.5
	*/
	function transfered() 
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		global $mainframe, $option;

		//Initialise variables
		$session = & JFactory::getSession();
		$db		= & JFactory::getDBO();
		$user		= & JFactory::getUser();

		//Get data session transfer
		$post		= $session->get('datatransfer', array(), $option);
		
		if( $session->has('session',$option) ) 
		{
			//Get the model
			$model = $this->getModel('Ownservice');

			// Get rate
			$rate	= $model->getRate();

			for($i=0,$n=count($post['account']); $i<$n; $i++) 
			{
				if($post['amount_dollar'][$i]) 
				{
					$data = array();

					$data['account'] =  $post['account'][$i];
					
					if(strtolower($post['reason'][$i]) == 'other') 
					{
						$data['reason']				= strtolower($post['reason'][$i]);
						$data['reason_other']	= $post['other'][$i];
					} else {
						$data['reason']				= $post['reason'][$i];
					}

					// set data
					$data['user_id']		= $user->get('id');
					$data['rate_id']			= $rate->id;
					$data['rate_th']		= $rate->rate_th;
					$data['rate']			= $rate->rate;
					$data['amount']		= $post['amount_dollar'][$i];
					$data['rate_code']	= $rate->code;
					$data['comment']		= $post['comment'][$i];

					//get fee
					$query = "SELECT fee FROM `#__ownservice_fees` "
								." WHERE `rate_id` =".$rate->id
								." AND `type` = 'fee' "
								." AND `from` <=".$data['amount']
								." AND `to` >=".$data['amount']
								;
					$db->setQuery($query);
					$fee = $db->loadResult();

					$data['fee'] = $fee;

					//get destination fee
					$query = "SELECT fee FROM `#__ownservice_fees` "
								." WHERE `rate_id` =".$rate->id
								." AND `type` = 'destinationfee' "
								." AND `from` <=".$data['amount']
								." AND `to` >=".$data['amount']
								;
					$db->setQuery($query);
					$bankfee = $db->loadResult();

					$data['bankfee'] = $bankfee;

					if( !$model->store($data) ) {
						JError::raiseError( 500, $model->getError() );
						return;
					}
				}
			}

			// Clear session 
			$session->clear( 'session', $option );
		}

		// Create the view
		$view		= & $this->getView('ownservice', 'html');

		$model	= $this->getModel('Ownservice');

		// Push the model into the view (as default)
		$view->setModel($model,true);

		// Set the layout
		$view->setLayout('message');

		// Display the view
		$view->display();
	}

	/**
	 * Method to get rate for exchange thai rate.
	 *
	 * @return numeric
	 * @since 1.5
	*/
	function thaiRate(){

		$db  	= & JFactory::getDBO();
		$user 	= & JFactory::getUser();
		$id 	= $user->get('id');

		//Get var
		$amount = JRequest::getVar('amount', 0);

		//Get data form the model
		$model = $this->getModel('ownservice');
		
		//Get branch ID
		$query = ' SELECT p.branch_id FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.(int) $id;
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();

		//Get rate
		$rate	= $model->getRate();

		//Get  fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate->id." AND `type` = 'fee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$fee = $db->loadResult();

		$fee = $fee?$fee:'0.00';
		
		//Get destination fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate->id." AND `type` = 'destinationfee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$bankfee = $db->loadResult();
		
		$bankfee = $bankfee?$bankfee:'0.00';

		$total = round( ($amount * $rate->rate ) - $bankfee , 2);


		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo "{'total': '".$total."', 'fee': '".$fee."', 'bankfee':'".$bankfee."'}";

		exit();
	}

	/**
	 * Method to get rate for exchange dollars rate.
	 *
	 * @return numeric
	 * @since 1.5
	*/
	function dollarRate() {

		$db 	=& JFactory::getDBO();
		$user 	=& JFactory::getUser();
		$id 	= $user->get('id');

		// Get var
		$sumtotal = JRequest::getVar('amount', 0);

		//Get data form the model
		$model 	= $this->getModel('ownservice');

		//Get branch ID
		$query 	= ' SELECT p.branch_id FROM #__users AS u '
				.' LEFT JOIN #__ownservice_users AS p ON p.user_id=u.id '
				.' WHERE u.id='.(int) $id;
				
		$db->setQuery($query);
		$branch_id = $db->loadResult();

		//Get rate
		$rate	= $model->getRate();

		$amount	= @round(($sumtotal / $rate->rate), 2);

		$num	= $this->calAmount($amount);
		
		$amount	= $amount+('0.0'.$num);

		//Get fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate->id." AND `type` = 'fee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$fee 	= $db->loadResult();

		$fee 	= $fee?$fee:'0.00';
		
		//Get destination fee
		$query = "SELECT fee FROM `#__ownservice_fees` WHERE `rate_id` =".$rate->id." AND `type` = 'destinationfee' AND `from` <=".$amount." AND `to` >=".$amount;
		$db->setQuery($query);
		$bankfee = $db->loadResult();
		
		$bankfee = $bankfee?$bankfee:'0.00';

		$amount = round( ($sumtotal+$bankfee) / $rate->rate , 2); //16/01/56

		$num	= $this->calAmount($amount);
		
		$amount	= $amount+('0.0'.$num);

		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
		header('Content-type: application/json');

		echo "{'amount': '".$amount."', 'fee': '".$fee."', 'bankfee':'".$bankfee."'}";

		exit();
	}

	function calAmount($amount)
	{
		list($a1, $a2)	= explode('.', $amount);
		$temp 			= substr($a2, -1);

		if($temp > 0 && $temp < 5){
			$num = 5 - $temp;
		} elseif($temp > 5){
			$num = 10 - $temp; 
		}else{
			$num = 0;
		}

		return $num;
	}


	/**
	 * logic for cancel an action
	 *
	 * @access public
	 * @return void
	 * @since 1.0
	 */
	function cancel()
	{
		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		global $option;

		$session = JFactory::getSession();

		if( $session->has('datatransfer',$option)) {
			$session->clear('datatransfer',$option);
		}

		$link = JRoute::_('index.php?option=com_ownservice');	

		$this->setRedirect( $link );
	}
}